package com.example.translateappjava.Utils;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.translateappjava.R;
import com.example.translateappjava.Utils.DataItem;

import java.util.List;

/**
 * Custom ArrayAdapter for displaying DataItem objects in a ListView or similar container.
 * Handles the inflation of layout and binding of image and text data to views.
 */
public class DataItemAdaptor extends ArrayAdapter<DataItem> {

    // Application context used for layout inflation
    private Context context;
    // Resource ID of the layout to be inflated for each item
    private int resource;
    // List of DataItem objects to be displayed
    private List<DataItem> dataItemList;

    /**
     * Constructor for the DataItem adapter
     * @param context The current context
     * @param resource The resource ID for a layout file containing the item views
     * @param dataItemList The list of DataItem objects to represent in the ListView
     */
    public DataItemAdaptor(@NonNull Context context, int resource, @NonNull List<DataItem> dataItemList) {
        super(context, resource, dataItemList);
        this.context = context;
        this.resource = resource;
        this.dataItemList = dataItemList;
    }

    /**
     * Gets a View that displays the data at the specified position
     * @param position The position of the item within the adapter's data set
     * @param convertView The old view to reuse, if possible
     * @param parent The parent that this view will eventually be attached to
     * @return A View corresponding to the data at the specified position
     */
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        // Inflate new view if no reusable view is available
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(resource, parent, false);
        }

        // Get the DataItem at the current position
        DataItem currentItem = dataItemList.get(position);

        // Get references to the views in the item layout
        ImageView itemImage = convertView.findViewById(R.id.item_image);
        TextView itemText = convertView.findViewById(R.id.item_text);

        // Bind data to the views
        itemImage.setImageResource(currentItem.getImageId());
        itemText.setText(currentItem.getContext());

        return convertView;
    }
}